import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { getAnswerResultList, logicalDeleteAnswerResult } from '../api/answerResult';
import { getTestScoreList } from '../api/testScore';
import { getAllRoles } from '../api/role';
import { getAllQuestionnaires } from '../api/questionnaire';
import { ElMessage } from 'element-plus';
import { getDoctorList } from '../api/doctor';
import { getBSHFList, insertBSHF } from '../api/bshf';
// 引入echarts
import * as echarts from 'echarts';

export default function useAnalysis() {
  const router = useRouter();
  const activeTab = ref('record');

  const resultList = ref([]);
  const loading = ref(false);

  // 角色和问卷映射表
  const roleMap = ref({});
  const questionnaireMap = ref({});

  // 图表相关
  const chartRef = ref(null);
  let chartInstance = null;

  // 雷达图相关
  const radarChartRef = ref(null);
  let radarChartInstance = null;

  // 辨识回访相关
  const dialogVisible = ref(false);
  const doctorList = ref([]);
  const bshfForm = ref({
    doctorId: '',
    resultId: null,
    quesnaireId: null,
    userinfoId: null
  });
  const currentResult = ref(null);

  // 体质类型映射
  const constitutionNames = {
    1: "平和质",
    2: "气虚质",
    3: "阳虚质",
    4: "阴虚质",
    5: "痰湿质",
    6: "湿热质",
    7: "血瘀质",
    8: "气郁质",
    9: "特禀质"
  };

  // 获取所有角色和问卷，建立映射表
  const loadRoleAndQuestionnaireMaps = async () => {
    try {
      // 获取角色
      const roleRes = await getAllRoles();
      if (roleRes?.code === 0 && Array.isArray(roleRes.data)) {
        roleMap.value = {};
        roleRes.data.forEach(role => {
          roleMap.value[role.id] = role.rolename;
        });
      }
      // 获取问卷
      const quesRes = await getAllQuestionnaires();
      if (quesRes?.code === 0 && Array.isArray(quesRes.data)) {
        questionnaireMap.value = {};
        quesRes.data.forEach(q => {
          questionnaireMap.value[q.id] = q.queslistName;
        });
      }
    } catch (e) {
      // 可选：错误提示
    }
  };

  // 获取当前用户ID（假设用户信息存在localStorage）
  const getCurrentUserId = () => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    return userInfo?.id || null;
  };

  // 获取答题记录
  const loadResults = async () => {
    try {
      loading.value = true;
      const userId = getCurrentUserId();
      
      if (!userId) {
        ElMessage.error('请先登录');
        return router.push('/login');
      }

      const res = await getAnswerResultList({ userinfoId: userId });
      if (res?.code === 0) {
        resultList.value = res.data;
      }
    } catch (error) {
      ElMessage.error('数据加载失败');
    } finally {
      loading.value = false;
    }
  };

  // 删除记录
  const handleDelete = async (id) => {
    try {
      await logicalDeleteAnswerResult(id);
      ElMessage.success('删除成功');
      resultList.value = resultList.value.filter(item => item.id !== id);
    } catch (error) {
      ElMessage.error('删除失败');
    }
  };

  // 解析体质类型
  const parseConstitutionType = (answerlistResult) => {
    try {
      const answerData = JSON.parse(answerlistResult);
      
      // 如果解析后的数据包含constitutionType字段，直接返回
      if (answerData && answerData.constitutionType) {
        return answerData.constitutionType;
      }
      
      // 兼容旧数据格式
      if (typeof answerData === 'string') return answerData;
      
      // 如果是对象，找出最高分的体质
      if (typeof answerData === 'object' && !Array.isArray(answerData)) {
        let maxScore = -1;
        let maxType = null;
        
        for (const key in answerData) {
          const score = parseFloat(answerData[key]);
          if (score > maxScore) {
            maxScore = score;
            maxType = key;
          }
        }
        
        return constitutionNames[maxType] || "未知体质";
      }
      
      return "未知体质";
    } catch (e) {
      console.error('解析体质类型失败:', e);
      return answerlistResult || "未知体质";
    }
  };

  // 获取体质追踪数据
  const getTrackData = () => {
    const sorted = [...resultList.value].sort((a, b) => 
      new Date(a.createTime) - new Date(b.createTime)
    );
    
    return sorted.map(item => ({
      date: item.createTime ? item.createTime.substring(0, 16).replace('T', ' ') : '',
      type: parseConstitutionType(item.answerlistResult)
    }));
  };

  // 渲染体质追踪图表
  const renderTrackChart = () => {
    if (!chartRef.value) return;
    
    if (!chartInstance) {
      chartInstance = echarts.init(chartRef.value);
    }
    
    const trackData = getTrackData();
    const dates = trackData.map(item => item.date);
    const types = trackData.map(item => item.type);
    
    // 获取所有可能的体质类型，包括复合体质
    const allTypes = [...new Set(types)];
    if (allTypes.length === 0) {
      // 如果没有数据，至少显示基本体质类型
      allTypes.push(...Object.values(constitutionNames));
    }
    
    chartInstance.setOption({
      backgroundColor: '#f9f6f2',
      title: {
        text: '体质变化趋势图',
        left: 'center',
        textStyle: {
          color: '#8B5C2A',
          fontFamily: 'KaiTi, SimSun, serif',
          fontSize: 24,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          const p = params[0];
          return `<div style="font-family:KaiTi;padding:5px;">
                    <div style="font-weight:bold;">${p.axisValue}</div>
                    <div>体质类型：<span style="color:${p.color};">${p.data}</span></div>
                  </div>`;
        },
        backgroundColor: 'rgba(255, 248, 220, 0.9)',
        borderColor: '#D2B48C'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '15%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLine: { lineStyle: { color: '#B8860B' } },
        axisLabel: {
          color: '#8B4513',
          fontFamily: 'KaiTi',
          rotate: 30
        }
      },
      yAxis: {
        type: 'category',
        data: allTypes,
        axisLine: { lineStyle: { color: '#B8860B' } },
        axisLabel: {
          color: '#8B4513',
          fontFamily: 'KaiTi'
        }
      },
      series: [{
        name: '体质类型',
        type: 'line',
        data: types,
        symbol: 'emptyCircle',
        symbolSize: 15,
        lineStyle: {
          color: '#CD853F',
          width: 3,
          shadowBlur: 10
        },
        itemStyle: {
          color: params => {
            const colors = [
              '#8B4513', '#CD853F', '#4682B4', '#FF6347', '#2E8B57', 
              '#FF8C00', '#8B0000', '#483D8B', '#9932CC'
            ];
            return colors[params.dataIndex % colors.length];
          },
          borderColor: '#FFF8DC',
          borderWidth: 2,
          shadowBlur: 10
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          fontFamily: 'KaiTi'
        },
        smooth: true
      }]
    });
  };

  // 渲染雷达图方法
  const renderRadarChart = async () => {
    if (!radarChartRef.value) return;
    
    if (!radarChartInstance) {
      radarChartInstance = echarts.init(radarChartRef.value);
    }

    try {
      // 获取按时间排序的所有答题记录
      const sortedResults = [...resultList.value].sort((a, b) => 
        new Date(a.createTime) - new Date(b.createTime)
      );

      // 并行获取所有测试分数数据
      const scorePromises = sortedResults.map(result => 
        getTestScoreList({ resultId: result.id })
      );
      const scoreResponses = await Promise.all(scorePromises);

      // 处理分数数据
      const seriesData = [];
      const indicators = [];
      
      // 生成雷达图指标（按体质ID排序）
      const sortedConstitutionIds = Object.keys(constitutionNames)
        .sort((a, b) => a - b)
        .map(Number);

      // 构建指标
      sortedConstitutionIds.forEach(id => {
        indicators.push({
          name: constitutionNames[id],
          max: 100
        });
      });

      // 构建每次测试的数据
      sortedResults.forEach((result, index) => {
        const scores = scoreResponses[index]?.data || [];
        const scoreMap = {};
        
        // 将分数转换为映射
        scores.forEach(score => {
          scoreMap[score.constitutionId] = score.score;
        });

        // 按排序后的体质ID生成数值数组
        const values = sortedConstitutionIds.map(id => 
          parseFloat(scoreMap[id] || 0)
        );

        // 获取体质类型名称（包括复合体质）
        const constitutionType = parseConstitutionType(result.answerlistResult);

        seriesData.push({
          value: values,
          name: `第${index + 1}次: ${constitutionType}`,
          lineStyle: {
            color: `rgb(${139 - index * 10}, ${69 - index * 5}, ${19 + index * 5})`
          }
        });
      });

      // 设置雷达图选项
      radarChartInstance.setOption({
        backgroundColor: '#f9f6f2',
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const values = params.value;
            let html = `<div style="font-family:KaiTi;padding:5px;">
                        <div style="font-weight:bold;margin-bottom:5px;">${params.name}</div>`;
            
            indicators.forEach((item, index) => {
              html += `<div>${params.marker} ${item.name}: ${values[index]}</div>`;
            });
            
            html += '</div>';
            return html;
          },
          backgroundColor: 'rgba(255, 248, 220, 0.9)',
          borderColor: '#D2B48C'
        },
        legend: {
          data: seriesData.map(d => d.name),
          bottom: 0,  // 调整到底部
          itemGap: 10, // 增加图例项之间的间距
          padding: [5, 10], // 增加内边距
          textStyle: {
            color: '#8B4513',
            fontFamily: 'KaiTi',
            fontSize: 12 // 减小字体大小
          },
          pageButtonItemGap: 5, // 翻页按钮与图例项的间距
          pageButtonPosition: 'end', // 翻页按钮位置
          pageIconSize: 12, // 翻页按钮大小
          pageTextStyle: { color: '#8B4513' } // 翻页文字样式
        },
        grid: {
          bottom: '15%' // 确保底部有足够空间放置图例
        },
        radar: {
          indicator: indicators,
          shape: 'circle',
          splitNumber: 5,
          center: ['50%', '45%'], // 将雷达图中心点向上移动
          radius: '65%', // 适当缩小雷达图半径
          axisName: {
            color: '#8B4513',
            fontFamily: 'KaiTi'
          },
          splitArea: {
            areaStyle: {
              color: ['rgba(255, 248, 220, 0.3)', 'rgba(245, 222, 179, 0.3)']
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(139, 69, 19, 0.3)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(139, 69, 19, 0.3)'
            }
          }
        },
        series: [{
          type: 'radar',
          data: seriesData,
          areaStyle: {
            opacity: 0.2
          },
          lineStyle: {
            width: 2
          },
          emphasis: {
            lineStyle: {
              width: 4
            }
          }
        }]
      });

    } catch (error) {
      console.error('渲染雷达图失败:', error);
      ElMessage.error('数据加载失败');
    }
  };

  const roleDialogVisible = ref(false);
  const roleForm = ref({
    roleId: ''
  });
  const allRoles = ref([]);
  const currentFollowup = ref(null);
  
  // 加载所有角色
  const loadAllRoles = async () => {
    try {
      const res = await getAllRoles();
      if (res?.code === 0 && Array.isArray(res.data)) {
        allRoles.value = res.data;
      }
    } catch (error) {
      console.error('加载角色数据失败:', error);
      ElMessage.error('角色数据加载失败');
    }
  };
  
  // 打开角色选择弹窗
  const openRoleDialog = (item) => {
    currentFollowup.value = item;
    roleForm.value.roleId = '';
    loadAllRoles();
    roleDialogVisible.value = true;
  };
  
  // 跳转到测试页面
  const goToTest = () => {
    if (!roleForm.value.roleId) {
      return ElMessage.warning('请选择角色');
    }
    
    if (!currentFollowup.value) {
      return ElMessage.warning('数据错误，请重试');
    }
    
    // 获取问卷版本
    const questionnaireVersion = questionnaireMap.value[currentFollowup.value.quesnaireId] || '详细版';
    
    // 构建路由
    const routePath = `/test?role=${encodeURIComponent(roleForm.value.roleId)}&version=${encodeURIComponent(questionnaireVersion)}&dId=${currentFollowup.value.doctorId}`;
    
    // 关闭弹窗
    roleDialogVisible.value = false;
    
    // 跳转
    router.push(routePath);
  };


  // 加载医生列表
  const loadDoctorList = async () => {
    try {
      const res = await getDoctorList({ status: '值班', del: 0 });
      if (res?.code === 0 && Array.isArray(res.data)) {
        doctorList.value = res.data;
      } else {
        ElMessage.warning('没有找到值班医生');
      }
    } catch (error) {
      console.error('加载医生列表失败:', error);
      ElMessage.error('加载医生列表失败');
    }
  };

  // 新增回访相关变量
  const followupList = ref([]);
  const followupLoading = ref(false);
  const doctorMap = ref({});

  // 格式化日期函数
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };

  // 加载医生映射
  const loadDoctorMap = async () => {
    try {
      const res = await getDoctorList();
      if (res?.code === 0 && Array.isArray(res.data)) {
        doctorMap.value = {};
        res.data.forEach(doctor => {
          doctorMap.value[doctor.id] = doctor.name;
        });
      }
    } catch (error) {
      console.error('加载医生数据失败:', error);
    }
  };

  // 加载回访数据
  const loadFollowupData = async () => {
    try {
      followupLoading.value = true;
      const userId = getCurrentUserId();
      
      if (!userId) {
        ElMessage.error('请先登录');
        return router.push('/login');
      }
      
      const res = await getBSHFList({
        userinfoId: userId,
        status: '回访中',
        del: 0
      });
      
      if (res?.code === 0) {
        followupList.value = res.data || [];
      } else {
        followupList.value = [];
      }
    } catch (error) {
      console.error('加载回访数据失败:', error);
      ElMessage.error('数据加载失败');
      followupList.value = [];
    } finally {
      followupLoading.value = false;
    }
  };

  // 处理提交辨识按钮点击
  const handleSubmitBSHF = (item) => {
    currentResult.value = item;
    bshfForm.value.resultId = item.id;
    bshfForm.value.quesnaireId = item.queslistId;
    bshfForm.value.userinfoId = getCurrentUserId();
    loadDoctorList();
    dialogVisible.value = true;
  };

  // 处理弹窗关闭
  const handleDialogClose = () => {
    dialogVisible.value = false;
    bshfForm.value.doctorId = '';
    currentResult.value = null;
  };

  // 提交辨识回访
  const submitBSHF = async () => {
    if (!bshfForm.value.doctorId) {
      return ElMessage.warning('请选择医生');
    }
    
    try {
      // 先查询是否已存在相同条件的记录
      const queryParams = {
        doctorId: bshfForm.value.doctorId,
        resultId: bshfForm.value.resultId,
        userinfoId: bshfForm.value.userinfoId,
        quesnaireId: bshfForm.value.quesnaireId,
        del: 0
      };
      
      const existRes = await getBSHFList(queryParams);
      
      if (existRes?.code === 0 && existRes.data && existRes.data.length > 0) {
        ElMessage.warning('您已提交结果给该医生进行辨识');
        dialogVisible.value = false;
        return;
      }
      
      // 不存在记录，执行插入操作
      const data = {
        doctorId: bshfForm.value.doctorId,
        resultId: bshfForm.value.resultId,
        userinfoId: bshfForm.value.userinfoId,
        quesnaireId: bshfForm.value.quesnaireId,
        status: '未辨识' // 修改状态为"未辨识"
      };
      
      const res = await insertBSHF(data);
      if (res?.code === 0) {
        ElMessage.success('提交辨识成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error(res?.msg || '提交失败');
      }
    } catch (error) {
      console.error('提交辨识失败:', error);
      ElMessage.error('提交辨识失败');
    }
  };

  // 处理窗口大小变化
  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
    if (radarChartInstance) {
      radarChartInstance.resize();
    }
  };

  // 生命周期钩子
  onMounted(async () => {
    await loadRoleAndQuestionnaireMaps();
    await loadDoctorMap(); // 加载医生映射
    await loadResults(); // 无论哪个tab都先加载数据
    
    if (activeTab.value === 'track') {
      nextTick(() => {
        renderTrackChart();
        renderRadarChart();
      });
    } else if (activeTab.value === 'followup') {
      // 如果初始选项卡是回访，加载回访数据
      loadFollowupData();
    }
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);
  });

  // 监听选项卡变化
  watch(activeTab, (newVal) => {
    if (newVal === 'track') {
      nextTick(() => {
        // 确保DOM已更新后再初始化图表
        setTimeout(() => {
          // 确保图表容器有尺寸
          if (chartRef.value && chartRef.value.offsetHeight === 0) {
            chartRef.value.style.height = '400px';
          }
          if (radarChartRef.value && radarChartRef.value.offsetHeight === 0) {
            radarChartRef.value.style.height = '450px'; // 增加雷达图高度
          }
          
          // 如果实例已存在，先销毁再重新创建
          if (chartInstance) {
            chartInstance.dispose();
            chartInstance = null;
          }
          if (radarChartInstance) {
            radarChartInstance.dispose();
            radarChartInstance = null;
          }
          
          // 重新渲染图表
          renderTrackChart();
          renderRadarChart();
        }, 300); // 增加延时确保DOM完全渲染
      });
    } else if (newVal === 'followup') {
      // 加载回访数据
      loadFollowupData();
    }
  });

  // 监听数据变化
  watch(resultList, () => {
    if (activeTab.value === 'track') {
      nextTick(() => {
        renderTrackChart();
        renderRadarChart();
      });
    }
  });

  // 组件卸载时清理
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    // 销毁图表实例
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    if (radarChartInstance) {
      radarChartInstance.dispose();
      radarChartInstance = null;
    }
  });

  return {
    activeTab,
    resultList,
    loading,
    roleMap,
    questionnaireMap,
    chartRef,
    radarChartRef,
    dialogVisible,
    doctorList,
    bshfForm,
    currentResult,
    handleDelete,
    parseConstitutionType,
    handleSubmitBSHF,
    handleDialogClose,
    submitBSHF,
    // 新增回访相关返回值
    followupList,
    followupLoading,
    doctorMap,
    formatDate,
    // 添加角色选择相关
    roleDialogVisible,
    roleForm,
    allRoles,
    openRoleDialog,
    goToTest
  };
}
